<?php
/**
 * Created by PhpStorm.
 * User: yiduan
 * Date: 2019/2/15 0015
 * Time: 14:33
 */
namespace app\app\controller;
use think\Controller;
use think\Db;

class Common extends Controller
{
    protected $requestType = 'get';
    private $pgData;

    public function __construct(\think\App $app = null)
    {
        if(!$this->fmtData()){
            die(json_encode(['code'=>1000, 'msg' => '参数错误！'], JSON_UNESCAPED_UNICODE));
        }
        parent::__construct($app);
    }

    /**
     * @param string $type
     * @return string
     */
    public function fmtData($type = ''){
        if(!$type){
            $type = $this->requestType;
        }
        $vg = input($type . '.');
        if(!empty($vg)){
            $this->pgData = $vg;
            return $vg;
        }
        return true;
    }

    /**
     * 返回pgData某项内容 或者 整个 pgData
     * @param string $key
     * @return string
     */
    public function getPgData($key = '', $default = 'defaultValue@@df'){
        if($key){
            $reVal =  isset($this->pgData[$key]) ? $this->pgData[$key] : '';
            if(!$reVal && $default != 'defaultValue@@df'){
                return $default;
            }
            return $reVal;
        }
        return $this->pgData;
    }

    /**
     * 格式化返回结果
     * @param $code                 返回code码
     * @param array $data           返回数据
     * @param string $msg           返回提示消息
     * @param bool $return          返回处理的结果 或 直接输出处理后的结果并 exit
     * @return string               处理后的JSON串：{"code":0, "data":[],"msg":"ok"}
     */
    public function fmtResult($code,array $data = [], $msg = '', $return = false){
        if($code){
            if($codes = json_decode($code, true)){
                if(is_array($codes)){
                    if(!$msg){
                        $msg = $codes['msg'];
                    }
                    $code = $codes['code'];
                }
            }
        }

        unset($data['uid']);

        $reArr = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        if($return){
            return json_encode($reArr, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode($reArr, JSON_UNESCAPED_UNICODE);
            exit;
        }
    }
}